package com.wsoft.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wsoft.constant.RedisKeyConstant;
import com.wsoft.core.annotation.GetRedisCache;
import com.wsoft.core.annotation.InitRedisCache;
import com.wsoft.system.entity.SysMenuEntity;
import com.wsoft.system.entity.SysRoleMenuRelationEntity;
import com.wsoft.system.mapper.SysRoleMenuRelationMapper;
import com.wsoft.system.query.role.menu.RoleMenuQuery;
import com.wsoft.system.service.ISysMenuService;
import com.wsoft.system.service.ISysRoleMenuRelationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zgk
 * @since 2024年09月23日 09:18:25
 */
@Service
public class SysRoleMenuRelationServiceImpl extends ServiceImpl<SysRoleMenuRelationMapper, SysRoleMenuRelationEntity> implements ISysRoleMenuRelationService {

    @Resource
    private ISysMenuService menuService;

    @Override
    @GetRedisCache(type = RedisKeyConstant.ROLE_MENU_CACHE,
                    value = RedisKeyConstant.REDIS_SELF)
    public List<SysMenuEntity> getMenuListByRoleId(Long roleId) {
        QueryWrapper<SysRoleMenuRelationEntity> query = new QueryWrapper<>();
        query.lambda().eq(SysRoleMenuRelationEntity::getRoleId,roleId);
        List<SysRoleMenuRelationEntity> list = list(query);
        List<Long> menuIds = list.stream().map(SysRoleMenuRelationEntity::getMenuId).collect(Collectors.toList());
        if (menuIds.size() == 0){
            return new ArrayList<>();
        }
        return menuService.listByIds(menuIds);
    }

    @Override
    @InitRedisCache(type = RedisKeyConstant.ROLE_MENU_CACHE,
                    value = "roleId")
    @Transactional(rollbackFor = Exception.class)
    public boolean insertRelationByRoleId(RoleMenuQuery query) {
        //清空角色菜单关系
        deleteByRoleId(query.getRoleId());
        //新增角色菜单关系
        if (query.getMenuIds() != null && query.getMenuIds().size() > 0) {
            List<SysRoleMenuRelationEntity> list = new ArrayList<>();
            for (Long menuId : query.getMenuIds()) {
                SysRoleMenuRelationEntity relation = new SysRoleMenuRelationEntity();
                relation.setRoleId(query.getRoleId());
                relation.setMenuId(menuId);
                list.add(relation);
            }
            return saveBatch(list);
        }
        return true;
    }

    private void deleteByRoleId(Long roleId){
        QueryWrapper<SysRoleMenuRelationEntity> query = new QueryWrapper<>();
        query.lambda().eq(SysRoleMenuRelationEntity::getRoleId,roleId);
        remove(query);
    }
}
